package com.iotmonitor.iot.service.impl;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

import com.iotmonitor.common.core.utils.DateUtils;
import com.iotmonitor.iot.domain.dto.*;
import com.iotmonitor.iot.mapper.TdEngineMapper;
import com.iotmonitor.iot.service.ITbAlarmService;
import com.iotmonitor.iot.domain.TbAlarm;
import com.iotmonitor.iot.mapper.TbAlarmMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 报警配置Service业务层处理
 *
 * @author 1655
 * @date 2023-08-11
 */
@Service
public class TbAlarmServiceImpl implements ITbAlarmService {
    @Autowired
    private TbAlarmMapper tbAlarmMapper;

    @Autowired
    private TdEngineMapper tdEngineMapper;


    /**
     * 查询报警配置
     *
     * @param id 报警配置主键
     * @return 报警配置
     */
    @Override
    public TbAlarm selectTbAlarmById(Long id) {
        return tbAlarmMapper.selectTbAlarmById(id);
    }

    /**
     * 查询报警配置列表
     *
     * @param tbAlarm 报警配置
     * @return 报警配置
     */
    @Override
    public List<TbAlarm> selectTbAlarmList(TbAlarm tbAlarm) {
        return tbAlarmMapper.selectTbAlarmList(tbAlarm);
    }

    /**
     * 新增报警配置
     *
     * @param tbAlarm 报警配置
     * @return 结果
     */
    @Override
    public int insertTbAlarm(TbAlarm tbAlarm) {
        return tbAlarmMapper.insertTbAlarm(tbAlarm);
    }

    /**
     * 修改报警配置
     *
     * @param tbAlarm 报警配置
     * @return 结果
     */
    @Override
    public int updateTbAlarm(TbAlarm tbAlarm) {
        return tbAlarmMapper.updateTbAlarm(tbAlarm);
    }

    /**
     * 批量删除报警配置
     *
     * @param ids 需要删除的报警配置主键
     * @return 结果
     */
    @Override
    public int deleteTbAlarmByIds(Long[] ids) {
        return tbAlarmMapper.deleteTbAlarmByIds(ids);
    }

    /**
     * 删除报警配置信息
     *
     * @param id 报警配置主键
     * @return 结果
     */
    @Override
    public int deleteTbAlarmById(Long id) {
        return tbAlarmMapper.deleteTbAlarmById(id);
    }

    /**
     * 告警日志查询
     *
     * @return
     */
    @Override
    public List<?> queryAlarmLog(String alarmName, String deviceId, String start, String end) {
        return tdEngineMapper.selectQuotaList(alarmName, deviceId, start, end);
    }

    @Override
    public List<TbAlarm> getByQuotaId(Long quotaId) {
        return tbAlarmMapper.queryByQuotaId(quotaId);
    }


    @Override
    public TbAlarm verifyQuota(QuotaDTO quotaDTO) {
        // 1.根据指标id查询告警判断规则列表
        List<TbAlarm> alarmEntityList = getByQuotaId(quotaDTO.getId());
        TbAlarm alarm = null;
        for (TbAlarm alarmEntity : alarmEntityList) {
            // 判断：操作符和指标对比
            if ("String".equals(quotaDTO.getValueType()) || "Boolean".equals(quotaDTO.getValueType())) {
                if ("=".equals(alarmEntity.getOperator()) && quotaDTO.getStringValue().equals(alarmEntity.getThreshold())) {
                    alarm = alarmEntity;
                    break;
                }
            } else // 数值
            {
                if (">".equals(alarmEntity.getOperator()) && quotaDTO.getValue() > alarmEntity.getThreshold() || "&gt;".equals(alarmEntity.getOperator()) && quotaDTO.getValue() > alarmEntity.getThreshold()) {
                    alarm = alarmEntity;
                    break;
                }
                if ("<".equals(alarmEntity.getOperator()) && quotaDTO.getValue() < alarmEntity.getThreshold() || "&lt;".equals(alarmEntity.getOperator()) && quotaDTO.getValue() > alarmEntity.getThreshold()) {
                    alarm = alarmEntity;
                    break;
                }
                if ("=".equals(alarmEntity.getOperator()) && quotaDTO.getValue().equals(alarmEntity.getThreshold().doubleValue())) {
                    alarm = alarmEntity;
                    break;
                }
            }
        }
        return alarm;
    }

    @Override
    public DeviceInfoDTO verifyDeviceInfo(DeviceInfoDTO deviceInfoDTO) {
        // 封装指标的告警  封装设备的告警
        DeviceDTO deviceDTO = deviceInfoDTO.getDevice();

        // 假设不告警
        deviceDTO.setLevel(0);
        deviceDTO.setAlarm(false);
        deviceDTO.setAlarmName("正常");
        deviceDTO.setStatus(true);
        deviceDTO.setOnline(true);

        for (QuotaDTO quotaDTO : deviceInfoDTO.getQuotaList()) {

            // 根据指标得到告警信息
            TbAlarm alarmEntity = verifyQuota(quotaDTO);
            if (alarmEntity != null) {
                // 如果指标存在告警
                // 如果有，则查询上一个错误警告并对比时间，如果在沉默周期内，则不予保存信息
                List<QuotaInfo> quotainfos = tdEngineMapper.getLastDataByDeviceIdAndAlarmName(deviceInfoDTO.getDevice().getDeviceId(), alarmEntity.getName());

                quotaDTO.setAlarm("1");
                // 告警名称
                quotaDTO.setAlarmName(alarmEntity.getName());
                // 告警级别
                quotaDTO.setLevel(alarmEntity.getLevel() + "");
                // 告警web钩子
                quotaDTO.setAlarmWebHook(alarmEntity.getWebhook());
                // 沉默周期
                quotaDTO.setCycle(alarmEntity.getCycle());

                // 当前时间减去沉默周期<ts则返回空
                if(quotainfos.size() != 0 && quotainfos.get(0).getTs().getTime() + alarmEntity.getCycle() * 60 * 1000 > System.currentTimeMillis()){
                    return null;
                }
                if (alarmEntity.getLevel().intValue() > deviceDTO.getLevel().intValue()) {
                    deviceDTO.setLevel(alarmEntity.getLevel());
                    deviceDTO.setAlarm(true);
                    deviceDTO.setAlarmName(alarmEntity.getName());
                }

            } else {// 如果指标不存储在告警
                quotaDTO.setAlarm("0");
                quotaDTO.setAlarmName("正常");
                quotaDTO.setLevel("0");
                quotaDTO.setAlarmWebHook("");
                quotaDTO.setCycle(0);
            }
        }
        return deviceInfoDTO;
    }


}
